package com.yougou.sub_server.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadPoolExecutor;

import javax.management.MXBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yougou.sub_server.model.InfoPublishContent;

@ManagedResource
public class Receiver {

	Logger logger = LoggerFactory.getLogger(Receiver.class);
	private ThreadPoolExecutor executor;

	public Receiver(ThreadPoolExecutor executor) {
		this.executor = executor;
	}

	@ManagedOperation
	public void receiveMessage(String message) throws NoSuchAlgorithmException {
		System.out.println(System.currentTimeMillis());
		ObjectMapper objectMapper = new ObjectMapper();
		InfoPublishContent infoPublishContent;
		try {
			infoPublishContent = objectMapper.readValue(message, InfoPublishContent.class);
			executor.execute(new Writehtml(infoPublishContent));
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
}

@ManagedResource
class Writehtml implements Runnable {
	Logger logger = LoggerFactory.getLogger(Writehtml.class);

	private InfoPublishContent infoPublishContent;
  
	public Writehtml(InfoPublishContent infoPublishContent) {
		super();
		this.infoPublishContent = infoPublishContent;
	}

	@Override
	public void run() {
		String path = "/data/" + infoPublishContent.getFilePath();
		String content = infoPublishContent.getContent();
		File file = new File(path);
		try {
			OutputStream outputStream = new FileOutputStream(file);
			outputStream.write(content.getBytes());
			System.out.println(System.currentTimeMillis());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
}